package mail.server;

import mail.account.UserAccount;
import mail.account.UserAccountList;
import mail.attribute.MailItem;
import java.io.File;
import java.util.List;

/**
 * A simple model of a mail server. The server is able to receive
 * mail items for storage, and deliver them to clients on demand.
 * @author David J. Barnes and Michael Kolling
 * @version 2006.03.30
 */
public class MailServer {

    public static final String DEFAULT_FOLDER = System.getProperty("user.home") + "/mailconf";
    // Storage for the arbitrary number of mail items to be stored
    // on the server.    
    private MailBox mailBox;
    private String localDirectory;
    private UserAccountList serverAccountsList;

    public static MailServer createServer(String path) {
        File directory = new File(path);
        if (!directory.exists()) {
            throw new IllegalArgumentException("Invalid path : " + path);
        }
        return new MailServer(path);
    }

    public static MailServer createServer() {
        return createServer(DEFAULT_FOLDER);
    }

    /**
     * Construct a mail server.
     */
    private MailServer(String directory) {
        this.localDirectory = directory;
        mailBox = new PersistentMailBox(directory);
    }
    
    
    public MailServer() {
        this(DEFAULT_FOLDER);
    }

    /**
     * Return how many mail items are waiting for a user.
     * @param who The user to check for.
     * @return How many items are waiting.
     */
    public int howManyMailItems(UserAccount who) {
        return mailBox.howManyMailItems(who);
    }

    /**
     * Return the next mail item for a user or null if there
     * are none.
     * @param who The user requesting their next item.
     * @return The user's next item.
     */
    public MailItem getNextMailItem(UserAccount who) {
        return mailBox.getNextMail(who);
    }

    /**
     * Add the given mail item to the message list.
     * @param item The mail item to be stored on the server.
     */
    public void post(MailItem item) {
        if (item.accountsExist(serverAccountsList)) {
            mailBox.post(item);
        }
    }

    public void addAccountsServer(String user) {
        serverAccountsList = new UserAccountList(localDirectory + "/mail.config");
        serverAccountsList.addAccount(user);
    }

    public boolean existsAccountInServer(String user) {
        serverAccountsList = new UserAccountList(localDirectory + "/mail.config");
        return serverAccountsList.contains(new UserAccount(user));
    }

    public List<MailItem> fetchMailsFromUser(UserAccount user) {
        return mailBox.getAllMails(user);
    }

    public void deleteMail(UserAccount user, MailItem item) {
        mailBox.remove(user, item);
    }

    public void deleteAllMailFromUser(UserAccount user) {
        List<MailItem> item = mailBox.getAllMails(user);
        for (MailItem mailItem : item) {
            mailBox.remove(user, mailItem);
        }
    }
}